package com.example.weather_app;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.weather_app.base.BaseFragment;
import com.example.weather_app.base.HttpUtils;
import com.example.weather_app.base.URLUtils;
import com.example.weather_app.bean.IndexBean;
import com.example.weather_app.bean.WeatherBean;
import com.example.weather_app.db.DBManager;
import com.google.gson.Gson;

import java.util.List;

public class CityFragment extends BaseFragment implements View.OnClickListener {

    //Today
    private TextView fragTvCurrenttemp;
    private TextView fragTvCity;
    private TextView fragTvCondition;
    private TextView fragTvDate;
    private TextView fragTvWind;
    private TextView fragTvTemprange;
    private TextView fragIndexTvDress;
    private ImageView fragIvWeather;

    //Index
    private TextView fragIndexTvCar;
    private TextView fragTvCold;
    private TextView fragIvSport;
    private TextView fragTvRays;
    private TextView fragTvAir;

    //future
    private LinearLayout fragCenterLayout;

    //rootViewManager
    private View rootView;
    private ScrollView fragSv;

    //首选项
    SharedPreferences bg_pref;

    //数据库
    String city;

    //指数信息
    private IndexBean.ResultDTO.LifeDTO life;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取从Activity传入的参数
        Bundle bundle = getArguments();
        city = bundle.getString("city");
        String path = URLUtils.getTemp_url(city);
        //今日天气api网络请求与加载数据
        loadData(path);
        //TODO:指数api网络请求
        String indexPath = URLUtils.getIndex_url(city);
        loadIndexData(indexPath);
    }

    /**
     * 解析路径
     *
     * @param indexPath
     */
    Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 100) {
                String json = (String) msg.obj;
                //解析json
                IndexBean indexBean = new Gson().fromJson(json, IndexBean.class);
                if (indexBean.getError_code()!=0){
                    life = null;
                    Toast.makeText(getContext(), "今日访问次数已上限", Toast.LENGTH_SHORT).show();
                }else {
                    life = indexBean.getResult().getLife();
                }

            }
        }
    };

    private void loadIndexData(String indexPath) {
        //开启异步
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = HttpUtils.loadIndexData(indexPath);
                Message message = handler.obtainMessage();
                message.what = 100;
                message.obj = result;
                handler.sendMessage(message);
            }
        }).start();
    }

    @Override
    public void onSuccess(String result) {
        Log.i("TAG", "onSuccess: 请求成功");
        parseShowData(result);
        //数据库增加和更新操作
        int i = DBManager.updataInfoByCity(city, result);
        if (i <= 0) {
            //更新数据库失败
            DBManager.addCityInfo(city, result);
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        Log.i("TAG", "onError: 加载失败");
//        数据库当中查找上一次信息显示在Fragment当中
        String s = DBManager.queryInfoByCity(city);
        if (!TextUtils.isEmpty(s)) {
            parseShowData(s);
        }
    }

    //加载今日天气和未来天气
    private void parseShowData(String result) {
        Log.i("TAG", "parseShowData: ");
        WeatherBean bean = new Gson().fromJson(result, WeatherBean.class);
        WeatherBean.ResultDTO beanResult = bean.getResult();
        //温度
        WeatherBean.ResultDTO.RealtimeDTO realtime = beanResult.getRealtime();
        String temperature = realtime.getTemperature();
        fragTvCurrenttemp.setText(temperature + "℃");
        //城市
        String city = beanResult.getCity();
        fragTvCity.setText(city);
        //天气情况
        String info = realtime.getInfo();
        fragTvCondition.setText(info);
        //获取日期
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
//        Date date = new Date(System.currentTimeMillis());
//        fragTvDate.setText(simpleDateFormat.format(date));
        List<WeatherBean.ResultDTO.FutureDTO> future = beanResult.getFuture();
        WeatherBean.ResultDTO.FutureDTO futureDTO = future.get(0);
        String date = futureDTO.getDate();
        fragTvDate.setText(date);
        //风
        String wind = realtime.getDirect() + realtime.getPower();
        fragTvWind.setText(wind);
        //温度
        String temperature1 = parseTemperature(futureDTO.getTemperature());
        temperature1.replace("/", "~");
        Log.i("TAG", "parseShowData: " + temperature1);
        //获取未来三天的天气情况
        for (int i = 1; i < future.size(); i++) {
            View centerItem = getLayoutInflater().inflate(R.layout.item_main_center, null);
            fragCenterLayout.addView(centerItem);
            WeatherBean.ResultDTO.FutureDTO centerFuture = future.get(i);
            TextView idateTv = centerItem.findViewById(R.id.item_center_tv_date);
            TextView iconTv = centerItem.findViewById(R.id.item_center_tv_con);
            TextView itempTv = centerItem.findViewById(R.id.item_center_tv_temp);

            idateTv.setText(centerFuture.getDate());
            iconTv.setText(centerFuture.getWeather());
            String temperature2 = centerFuture.getTemperature();
            itempTv.setText(parseTemperature(temperature2.replace("/", "~")));

        }
    }

    public String parseTemperature(String temp) {
        temp.replace("/", "~");
        return temp;
    }

    @Override
    public void onCancelled(CancelledException cex) {

    }

    @Override
    public void onFinished() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_city, container, false);
        initView(rootView);
        exchangeBg();
        return rootView;
    }

    private void initView(View rootView) {
//        今日天气情况TextView
        fragTvCurrenttemp = (TextView) rootView.findViewById(R.id.frag_tv_currenttemp);
        fragTvCity = (TextView) rootView.findViewById(R.id.frag_tv_city);
        fragTvCondition = (TextView) rootView.findViewById(R.id.frag_tv_condition);
        fragTvDate = (TextView) rootView.findViewById(R.id.frag_tv_date);
        fragTvWind = (TextView) rootView.findViewById(R.id.frag_tv_wind);
        fragTvTemprange = (TextView) rootView.findViewById(R.id.frag_tv_temprange);

        //未来三天的天气情况
        fragCenterLayout = (LinearLayout) rootView.findViewById(R.id.frag_center_layout);

        //获取指数TextView
        fragIndexTvDress = (TextView) rootView.findViewById(R.id.frag_index_tv_dress);
        fragIndexTvCar = (TextView) rootView.findViewById(R.id.frag_index_car);
        fragTvCold = (TextView) rootView.findViewById(R.id.frag_index_cold);
        fragIvSport = (TextView) rootView.findViewById(R.id.frag_index_sport);
        fragTvRays = (TextView) rootView.findViewById(R.id.frag_index_rays);
        fragTvAir = (TextView) rootView.findViewById(R.id.frag_index_air);

        //设置监听事件
        fragIndexTvDress.setOnClickListener(this);
        fragIndexTvCar.setOnClickListener(this);
        fragTvCold.setOnClickListener(this);
        fragIvSport.setOnClickListener(this);
        fragTvRays.setOnClickListener(this);
        fragTvAir.setOnClickListener(this);

        //背景
        fragSv = rootView.findViewById(R.id.frag_sv);

        //首选项
        bg_pref = getActivity().getSharedPreferences("bg_pref", Context.MODE_PRIVATE);
    }

    private void exchangeBg() {
        int bg = bg_pref.getInt("bg", 0);
        switch (bg) {
            case 0:
                fragSv.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                fragSv.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                fragSv.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }

    //TODO:弹窗
    @Override
    public void onClick(View view) {
        //TODO:点击Index时进行处理
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        switch (view.getId()) {
            case R.id.frag_index_tv_dress:
                builder.setTitle("穿衣指数");
                if (life != null) {
                    builder.setMessage(life.getChuanyi().getV()
                            + "\n"
                            + life.getChuanyi().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
            case R.id.frag_index_car:
                builder.setTitle("洗车指数");
                if (life != null) {
                    builder.setMessage(life.getXiche().getV()
                            + "\n"
                            + life.getXiche().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
            case R.id.frag_index_cold:
                builder.setTitle("感冒指数");
                if (life != null) {
                    builder.setMessage(life.getGanmao().getV()
                            + "\n"
                            + life.getGanmao().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
            case R.id.frag_index_sport:
                builder.setTitle("运动指数");
                if (life != null) {
                    builder.setMessage(life.getYundong().getV()
                            + "\n"
                            + life.getYundong().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
            case R.id.frag_index_rays:
                builder.setTitle("紫外线指数");
                if (life != null) {
                    builder.setMessage(life.getZiwaixian().getV()
                            + "\n"
                            + life.getZiwaixian().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
            case R.id.frag_index_air:
                Log.i("TAG", "onClick: 111");
                builder.setTitle("空调指数");
                if (life != null) {
                    builder.setMessage(life.getKongtiao().getV()
                            + "\n"
                            + life.getKongtiao().getDes());
                } else {
                    builder.setMessage("暂无信息");
                }
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
        }
    }
}